package com.prodog.util;

import cn.hutool.core.io.FileUtil;
import com.prodog.gamemodule.config.DictConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.StringWriter;
import java.util.Map;

/***
 * 游戏配置/消息模板工具
 */
@Component
public class MsgTemplateUtil {
    private static String rootPath;
    private static Configuration cfg = new Configuration(new Version("2.3.23"));
    private static DictConfig dictConfig;

    @Value("${game.rootPath}")
    private void setRootPath(String rootPath) {
        MsgTemplateUtil.rootPath = rootPath;
    }

    @Autowired
    private void setDictConfig(DictConfig dictConfig) {
        MsgTemplateUtil.dictConfig = dictConfig;
    }

    public static String formatMsg(String path, Map<String, Object> params) {
        File file = new File(rootPath, path);
        String template;
        try {
            template = FileUtil.readUtf8String(file);
            StringWriter result = new StringWriter();
            dictConfig.getDicts().forEach((k, v) -> params.put("_" + k, v));
            Template tpl = new Template("strTpl", template, cfg);
            tpl.process(params, result);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String formatStr(String str, Map<String, Object> params) {
        try {
            StringWriter result = new StringWriter();
            dictConfig.getDicts().forEach((k, v) -> params.put("_" + k, v));
            Template tpl = new Template("strTpl", str, cfg);
            tpl.process(params, result);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
